package com.hotel.config.rabbitmq.dead;

import com.common.status.ResultMsg;
import com.hotel.config.rabbitmq.config.PersonalCouponWebSocketDirectConfig;
import com.hotel.config.websocket.WebSocketProcess;
import com.hotel.customersystem.controller.CustomerUserController;
import com.hotel.customersystem.controller.CustomerUserCouponController;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
public class PersonalCouponWebSocketDead {

    @Resource
    private WebSocketProcess webSocketProcess;

    @Resource
    private CustomerUserCouponController customerUserCouponController;

    @Resource
    private CustomerUserController customerUserController;

    /**
     * 优惠劵将要过期(前三天)想用户发送提醒
     * 并进入新的监听队列(优惠劵过期监听)
     */
    @RabbitHandler
    @RabbitListener(queues = PersonalCouponWebSocketDirectConfig.DEAD_PERSON_COUPON_WEBSOCKET_QUEUE)
    public void personCouponWebSocketListener(Message message, Channel channel){
        System.out.println("死信队列进行监听(websocket提醒)..."+new String(message.getBody()));
        String couponId = new String(message.getBody());
        System.out.println("死信队列发送请求的优惠劵id:"+couponId);
        //进入新的监听队列(优惠劵过期监听)
        customerUserCouponController.rabbitListenIsCancel(couponId);
        //返回对应用户id
        String customerUserId = customerUserCouponController.getCustomerUserId(Integer.valueOf(couponId));
        System.out.println("需要给用户发送 websocket "+customerUserId);
        try {
            webSocketProcess.sendAllMessage(ResultMsg.COUPON_WILL_CANCEL_WEBSOCKET_MSG + "-" + customerUserId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //消息确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
